package com.drinks.yiniang.ui.fragment.user.invoice;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.drinks.yiniang.R;
import com.drinks.yiniang.entity.common.StringJson;
import com.drinks.yiniang.io.api.InvoiceApiIO;
import com.drinks.yiniang.io.http.HttpUrls;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.ui.fragment.BaseFragment;
import com.hansen.library.utils.LogUtils;
import com.hansen.library.utils.StringUtils;

/**
 * 开票须知页面
 * A simple {@link Fragment} subclass.
 */
public class InvoiceNotesFragment extends BaseFragment {

    //发票须知
    private FrameLayout fl_invoice_notes_web;
    //去开票
    private Button btn_invoice_manage_make;
    //加载进度条
    private ProgressBar progress_invoice_notes;
    //webview
    private WebView mWebView;

    private OnToMakeInvoiceListener onToMakeInvoiceListener;

    public InvoiceNotesFragment() {
        // Required empty public constructor
    }

    public static InvoiceNotesFragment newInstance() {

        return new InvoiceNotesFragment();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            onToMakeInvoiceListener = (OnToMakeInvoiceListener) context;
        } catch (ClassCastException e) {
            LogUtils.e(context.toString() + "must implement OnToMakeInvoiceListener");
        }
    }

    @Override
    protected int getResID() {
        return R.layout.fragment_invoice_notes;
    }

    @Override
    protected void initView(View mView) {
        fl_invoice_notes_web = mView.findViewById(R.id.fl_invoice_notes_web);

        progress_invoice_notes = mView.findViewById(R.id.progress_invoice_notes);

        btn_invoice_manage_make = mView.findViewById(R.id.btn_invoice_manage_make);
    }

    @Override
    protected void initData() {
        mContext = getActivity();

        initWebView();
        getInvoiceNotes();
    }

    @Override
    protected void listener() {
        btn_invoice_manage_make.setOnClickListener(this);
    }

    @Override
    protected void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.btn_invoice_manage_make://去开票
                if (onToMakeInvoiceListener != null) {
                    onToMakeInvoiceListener.toMakeInvoice();
                }
                break;
            default:
                break;
        }
    }

    //发票须知
    private void getInvoiceNotes() {
        showLoadingDialog();

        InvoiceApiIO.getInstance().getInvoiceNotes(new APIRequestCallback<StringJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(StringJson res) {
                mWebView.loadDataWithBaseURL(HttpUrls.API_HOST, res.getData(), "text/html", "utf-8", null);
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //初始化webview
    private void initWebView() {
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

        mWebView = new WebView(mContext);

        mWebView.setBackgroundColor(0);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); //取消滚动条白边效果
        mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
        mWebView.getSettings().setBlockNetworkImage(false);
        mWebView.getSettings().setDomStorageEnabled(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(mWebView.getSettings().MIXED_CONTENT_ALWAYS_ALLOW);  //注意安卓5.0以上的权限
        }

        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress == 100) {
                    progress_invoice_notes.setVisibility(View.GONE);
                } else {
                    progress_invoice_notes.setProgress(newProgress);
                }
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message,
                                     JsResult result) {
                // TODO Auto-generated method stub
                return super.onJsAlert(view, url, message, result);
            }
        });

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (StringUtils.isHttp(url)) { //http和https协议开头的执行正常的流程
                    return false;
                }

                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        });


        fl_invoice_notes_web.addView(mWebView, params);
    }

    public interface OnToMakeInvoiceListener {
        void toMakeInvoice();
    }

    @Override
    public void onDestroy() {
        if (mWebView != null) {
            mWebView.stopLoading();
            mWebView.clearHistory();
            //webview.pauseTimers();
            mWebView.setWebChromeClient(null);
            mWebView.destroy();
            mWebView = null;
        }
        if (fl_invoice_notes_web != null) {
            fl_invoice_notes_web.removeAllViews();
            fl_invoice_notes_web = null;
        }
        super.onDestroy();
    }
}
